package com.xjj.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjj.common.BaseContext;
import com.xjj.common.R;
import com.xjj.entity.User;
import com.xjj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<User> login(@RequestBody User user, HttpSession session){
        log.info("user=====>{}",user);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,user.getPhone());

        User user1 = userService.getOne(queryWrapper);
        if (user1==null){
            userService.save(user);
            user1 = userService.getOne(queryWrapper);
        }
        session.setAttribute("user",user1.getId());
        return R.success(user1);
    }


    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request){
        BaseContext.setCurrentId(null);
        request.getSession().removeAttribute("user");
        return R.success("退出登录成功！");
    }
}
